#![allow(dead_code)]
use std::sync::Mutex;

use log::info;
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use crate::utils::http_client_app::HttpAppError;
use crate::utils::js_bridge::JsBridge;

/// 认证信息结构
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthInfo {
    pub token: String,
    pub token_id: String,
    pub expires: u64,
}

/// 全局认证状态
static AUTH_INFO: Lazy<Mutex<Option<AuthInfo>>> = Lazy::new(|| Mutex::new(None));

/// 获取认证信息
pub async fn get_auth_info() -> Option<AuthInfo> {
    let auth_info = AUTH_INFO.lock().unwrap().clone();
    if auth_info.is_none() || auth_info.as_ref().map_or(true, |info| info.token.is_empty()) {
        let auth_info = get_js_auth_info().await;
        return set_info(auth_info);
    }
    auth_info
}

pub async fn get_token() ->Result<String, HttpAppError> {
    let auth_info = get_auth_info().await;
    auth_info
        .filter(|info| !info.token.is_empty())
        .map(|info| info.token)
        .ok_or(HttpAppError::Custom(-2, "请先登录".into()))
}

/// 设置认证信息
pub fn set_auth_info(token: &str, token_id: &str, expires: u64, savejs: bool) -> Option<AuthInfo> {
    let auth_info = AuthInfo {
        token: token.to_string(),
        token_id: token_id.to_string(),
        expires,
    };
    let auth_info = set_info(Some(auth_info));
    if savejs { set_js_auth_info(auth_info.clone()); }
    auth_info
}

pub fn set_info(auth_info: Option<AuthInfo>) -> Option<AuthInfo> {
    *AUTH_INFO.lock().unwrap() = auth_info.clone();
    info!("设置认证信息: {:?}", auth_info);
    auth_info
}

//js触发
#[tauri::command]
pub async fn js_set_auth_info(token: &str, token_id: &str, expires: u64) -> Result<AuthInfo, String> {
    log::info!("【主程序】收到来自 JS 的认证信息: token={}, token_id={}, expires={}", token, token_id, expires);

    // if expires == 999 {
    //     clean_data().await.map_err(|e| format!("清理数据失败: {}", e))?;
    // }

    let result = set_auth_info(token, token_id, expires, false)
        .ok_or_else(|| "认证信息设置失败".to_string());
        
    if expires == 999 {
        log::info!("【主程序】收到来自 JS 的认证信息: 999");
        let _ = crate::service::syn_zh_service::syn_zh_with_time_update(1).await;
    }
    
    result
}

pub fn set_js_auth_info(auth_info: Option<AuthInfo>) -> Option<AuthInfo> {
    match JsBridge::sync_func::<AuthInfo, AuthInfo>("window.setJsAuthInfo", auth_info.clone(), 3000) {
        Ok(val) => log::info!("【执行setAuthInfo】成功完成,结果:{:?}", val),
        Err(e) => log::error!("【执行setAuthInfo】失败: {}", e),
    };
    auth_info
}

//获取js的authinfo
pub async fn get_js_auth_info() -> Option<AuthInfo> {
    // 方法1：显式指定泛型参数
    // JsBridge::sync_func::<(), AuthInfo>("window.getJsAuthInfo", None::<()>, 3000)
    //     .map(|val| {
    //         log::info!("【执行getAuthInfo】成功完成,结果:{:?}", val);
    //         val
    //     }).map_err(|e| log::error!("【执行getAuthInfo】失败: {}", e))
    //     .ok() // 将 Result 转换为 Option
    match JsBridge::async_func("window.getJsAuthInfo", None::<()>, 3000).await{
        Ok(val) => {
            log::info!("【执行getAuthInfo】成功完成,结果:{:?}", val);
            Some(val)
        },
        Err(e) => {
            log::error!("【执行getAuthInfo】失败: {}", e);
            None
        }
    }
}